package com.asialjim.wechat.spring.bean;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.filter.AssignableTypeFilter;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * <h1><em>ASIAL JIM JAVA DOC</em></h1><hr/>
 * <h2>CLASS DESCRIPTION <i>[ NAME: WeChatBeanImportSelector ]</i></h2><strong>
 * <p> select all off we chat bean class name
 * </strong><p><p><em>Copyright &copy; Asial Jim Co., LTD</em><hr/>
 *
 * @author Asial Jim &nbsp;&nbsp; <span>Email:<a href="mailto:asialjim@hotmail.com">asialjim@hotmail.com</a> &nbsp;&nbsp; <a href="asialjim@qq.com">asialjim@qq.com</a></span>
 * @version 1.0.0
 * @since 2021/4/2   &nbsp;&nbsp; JDK 8
 */
@Slf4j
public class WeChatBeanImportSelector implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata annotationMetadata) {
        Map<String, Object> annotationAttributes = annotationMetadata.getAnnotationAttributes(WeChatBeanSelector.class.getName());
        Class<?>[] beanClasses = (Class<?>[]) annotationAttributes.get("beanClass");
        String[] basePackages = (String[]) annotationAttributes.get("basePackage");
        Set<String> classes = new HashSet<>();

        for (Class<?> beanClass : beanClasses) {
            ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
            AssignableTypeFilter assignableTypeFilter = new AssignableTypeFilter(beanClass);
            scanner.addIncludeFilter(assignableTypeFilter);
            for (String basePackage : basePackages) {
                Set<BeanDefinition> candidateComponents = scanner.findCandidateComponents(basePackage);
                candidateComponents.forEach(beanDefinition -> classes.add(beanDefinition.getBeanClassName()));
            }
        }

        return classes.toArray(new String[classes.size()]);
    }
}
